import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'

export const getSkuCombinationStore = defineStore('skuCombinations', () => {
  const selectedAttrValues = ref([])
  const sourceData = ref([])

  interface SpuContentItem {
    fileData: any
    baseData: any
    order: number
    type: string
  }
  
  const formData = ref({
    categoryId: '',
    title: '',
    subTitle: '',
    spuContent: [] as SpuContentItem[],
    spuAttrList: reactive([]),
    skuDetailList: []
  })
  //默认有富文本组件
  formData.value.spuContent.push({
    fileData: null,
    baseData: null,
    order: 0,
    type: 'TEXT',
  })

  function getSkuCombination() {
    // 1. 根据 attrId 进行分组并去重 valueId
    const groupedValues = selectedAttrValues.value.reduce((acc, cur) => {
      if (!acc[cur.attrId]) {
        acc[cur.attrId] = []
      }
      if (!acc[cur.attrId].includes(cur.valueId)) {
        acc[cur.attrId].push(cur.valueId)
      }
      return acc
    }, {})

    const groupedArray = Object.values(groupedValues)
    // 2. 获取所有属性值的组合
    const combinations = ():Array<any> => {
      const result = [[]]
      for (const group of groupedArray) {
        const currentLength = result.length
        for (let i = 0; i < currentLength; i++) {
          for (const value of group) {
            result.push(result[i].concat(value))
          }
        }
      }
      return result.filter((comb) => comb.length > 0) // 过滤掉空组合
    }

    // 3. 根据组合生成对应的 name
    const getName = (valueIds) => {
      return valueIds
        .map((valueId) => {
          for (const attr of sourceData.value) {
            const attrValue = attr.attrValueDTOList.find((v) => v.id === valueId)
            if (attrValue) {
              return attr.name + '-' + attrValue.name
            }
          }
          return ''
        })
        .join('-')
    }

    // 4. 生成最终结果数组
    const result = combinations().map((combination) => ({
      valueId: combination,
      name: getName(combination),
      price:0,
      imgList:[]
    }))

    return result
  }

  return {
    selectedAttrValues,
    sourceData,
    getSkuCombination,
    formData
  }
})
